import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from 'vue-router'
import { setupRouterGuards } from './guards'
import { basicRoutes } from './basic-router'
import { usePermissionStore, useAuthStore } from '@/store'

export const router = createRouter({
  history:
    import.meta.env.VITE_USE_HISTORY === 'true'
      ? createWebHistory('/')
      : createWebHashHistory('/'),
  routes: basicRoutes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { left: 0, top: 0 }
    }
  },
})

export async function setupRouter(app) {
  try {
    await initUserAndPermissions()
  } catch (error) {
    console.error('🚀 初始化失败', error)
  }
  setupRouterGuards(router)
  app.use(router)
}

export async function initUserAndPermissions() {
  const permissionStore = usePermissionStore()
  const authStore = useAuthStore()

  if (!authStore.accessToken) {
    const route = unref(router.currentRoute)
    if (route.path !== '/login') {
      router.replace({
        path: '/login',
        query: route.query,
      })
    }
    return
  }

  if (permissionStore?.accessRoutes) {
    permissionStore.accessRoutes.forEach((route) => {
      !router.hasRoute(route.name) && router.addRoute(route)
    })
  }
}
